package org.fastsyncer.connector.framework;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.fastsyncer.common.constant.ConnectorConstant;
import org.fastsyncer.connector.ldap.LdapConnector;
import org.fastsyncer.connector.mysql.MysqlConnector;
import org.fastsyncer.connector.oracle.OracleConnector;
import org.fastsyncer.connector.redis.RedisConnector;
import org.fastsyncer.connector.sql.SqlMysqlConnector;
import org.fastsyncer.connector.sql.SqlOracleConnector;
import org.fastsyncer.connector.sqlserver.SqlServerConnector;
import org.fastsyncer.connector.webservice.WebServiceConnector;

public final class ConnectorFactory {

    private static volatile ConnectorFactory instance = null;

    private ConnectorFactory() {
    }

    public static ConnectorFactory getInstance() {
        if (null == instance) {
            synchronized (ConnectorFactory.class) {
                if (null == instance) {
                    instance = new ConnectorFactory();
                }
            }
        }
        return instance;
    }
    
    // 存放连接器实例
    private final static Map<String, Connector> MAP = new ConcurrentHashMap<String, Connector>();
    
    static {
        MAP.put(ConnectorConstant.MYSQL_CONNECTOR, MysqlConnector.getInstance());
        MAP.put(ConnectorConstant.ORACLE_CONNECTOR, OracleConnector.getInstance());
        MAP.put(ConnectorConstant.SQLSERVER_CONNECTOR, SqlServerConnector.getInstance());
        MAP.put(ConnectorConstant.LDAP_CONNECTOR, LdapConnector.getInstance());
        MAP.put(ConnectorConstant.REDIS_CONNECTOR, RedisConnector.getInstance());
        MAP.put(ConnectorConstant.WS_CONNECTOR, WebServiceConnector.getInstance());
        MAP.put(ConnectorConstant.SQL_MYSQL_CONNECTOR, SqlMysqlConnector.getInstance());
        MAP.put(ConnectorConstant.SQL_ORACLE_CONNECTOR, SqlOracleConnector.getInstance());
    }
    
    public Connector getConnector(String connectorName){
        return MAP.get(connectorName);
    }

    @SuppressWarnings("unchecked")
    public <T> T getConnector(String connectorName, Class<T> clazz){
        return (T) MAP.get(connectorName);
    }

    /**
     * 检查连接器是否可用
     * @param connector 连接器实例org.fastsyncer.connector.xxx.xxxConnector
     * @param config 连接器配置
     * @return boolean
     */
    public boolean isAlive(String connector, Object config) {
        Connector conn = getConnector(connector);
        if (null == conn) {
            return false;
        }
        return conn.isAlive(config);
    }
    
}
